/**
 * 临时数据库解决方案 - 开发测试用
 * EndoSight-UC 医疗AI系统
 *
 * 这是一个模拟MySQL接口的临时实现，用于开发和测试
 * 在MySQL认证问题解决之前使用
 */

import { createSecureLogger } from '../utils/secureLoggingConfig.js';

const logger = createSecureLogger({
  service: 'TempDB',
  logLevel: process.env.LOG_LEVEL || 'info'
});

// 模拟数据存储
const tempData = {
  doctors: new Map(),
  patients: new Map(),
  scoring_tasks: new Map(),
  scoring_results: new Map(),
  system_logs: []
};

// 自增ID计数器
const counters = {
  doctor_id: 1,
  patient_id: 1,
  task_id: 1,
  result_id: 1,
  log_id: 1
};

// 性能监控统计
const performanceStats = {
  totalQueries: 0,
  slowQueries: 0,
  averageQueryTime: 0,
  queryTimes: [],
  errorCount: 0,
  lastReset: new Date()
};

// 初始化数据库
const initializeDatabase = async () => {
  try {
    logger.info('正在初始化临时数据库...');

    // 创建默认管理员用户
    const bcrypt = await import('bcryptjs');
    const salt = await bcrypt.genSalt(10);
    const passwordHash = await bcrypt.hash('admin123', salt);

    const adminUser = {
      doctor_id: counters.doctor_id++,
      username: 'admin',
      password_hash: passwordHash,
      salt: salt,
      real_name: '系统管理员',
      department: '系统管理',
      title: '管理员',
      role: 3,
      status: 1,
      created_at: new Date(),
      updated_at: new Date()
    };

    tempData.doctors.set('admin', adminUser);
    logger.info('✅ 临时数据库初始化成功');
    logger.info('⚠️ 这是临时解决方案，请尽快配置MySQL');

    return true;
  } catch (error) {
    logger.error('❌ 临时数据库初始化失败:', error.message);
    throw error;
  }
};

// 测试连接
export const testConnection = async () => {
  const startTime = Date.now();

  try {
    logger.info('✅ 临时数据库连接测试成功');
    const responseTime = Date.now() - startTime;
    updatePerformanceStats('testConnection', responseTime, true);
    return true;
  } catch (error) {
    const responseTime = Date.now() - startTime;
    updatePerformanceStats('testConnection', responseTime, false);
    logger.error('❌ 临时数据库连接测试失败:', error.message);
    throw error;
  }
};

// 执行查询
export const query = async (sql, params = []) => {
  const startTime = Date.now();

  try {
    logger.debug(`执行模拟SQL: ${sql}`, params);

    let result = [];

    // 简单的SQL解析和模拟
    if (sql.includes('SELECT')) {
      result = handleSelect(sql, params);
    } else if (sql.includes('INSERT')) {
      result = handleInsert(sql, params);
    } else if (sql.includes('UPDATE')) {
      result = handleUpdate(sql, params);
    } else if (sql.includes('DELETE')) {
      result = handleDelete(sql, params);
    }

    const queryTime = Date.now() - startTime;
    updatePerformanceStats(sql, queryTime, true);
    logger.debug(`查询完成: ${result.length} 条记录，耗时: ${queryTime}ms`);

    return result;

  } catch (error) {
    const queryTime = Date.now() - startTime;
    updatePerformanceStats(sql, queryTime, false);

    logger.error('数据库查询失败:', {
      error: error.message,
      sql: sql,
      params: params
    });

    throw error;
  }
};

// 处理SELECT查询
const handleSelect = (sql, params) => {
  if (sql.includes('doctors') && sql.includes("username =")) {
    const username = params[0];
    const doctor = Array.from(tempData.doctors.values()).find(d => d.username === username);
    return doctor ? [doctor] : [];
  }

  if (sql.includes('scoring_tasks') && sql.includes('doctor_id =')) {
    const doctorId = params[0];
    return Array.from(tempData.scoring_tasks.values())
      .filter(task => task.doctor_id === doctorId)
      .sort((a, b) => new Date(b.submit_time) - new Date(a.submit_time));
  }

  if (sql.includes('scoring_results') && sql.includes('task_id =')) {
    const taskId = params[0];
    const result = Array.from(tempData.scoring_results.values())
      .find(r => r.task_id === taskId);
    return result ? [result] : [];
  }

  // 统计查询
  if (sql.includes('COUNT(*)')) {
    if (sql.includes('doctors')) {
      return [{ count: tempData.doctors.size }];
    } else if (sql.includes('patients')) {
      return [{ count: tempData.patients.size }];
    } else if (sql.includes('scoring_tasks')) {
      return [{ count: tempData.scoring_tasks.size }];
    } else if (sql.includes('scoring_results')) {
      return [{ count: tempData.scoring_results.size }];
    }
  }

  return [];
};

// 处理INSERT查询
const handleInsert = (sql, params) => {
  if (sql.includes('scoring_tasks')) {
    const newTask = {
      task_id: counters.task_id++,
      patient_id: params[0] || null,
      doctor_id: params[1],
      status: 1,
      submit_time: new Date(),
      complete_time: null,
      image_url: params[2] || null,
      clinical_text: params[3] || null,
      ai_inference_status: 0,
      ai_inference_time: null,
      ai_error_message: null
    };

    tempData.scoring_tasks.set(newTask.task_id, newTask);
    return [{ insertId: newTask.task_id }];
  }

  if (sql.includes('scoring_results')) {
    const newResult = {
      result_id: counters.result_id++,
      task_id: params[0],
      score: params[1],
      severity: params[2],
      confidence: params[3],
      model_version: params[4] || 'v1.0',
      analysis_details: params[5] || null,
      created_at: new Date()
    };

    tempData.scoring_results.set(newResult.result_id, newResult);
    return [{ insertId: newResult.result_id }];
  }

  return [];
};

// 处理UPDATE查询
const handleUpdate = (sql, params) => {
  if (sql.includes('scoring_tasks') && sql.includes('status =')) {
    const taskId = params[1];
    const task = tempData.scoring_tasks.get(taskId);
    if (task) {
      task.status = params[0];
      if (params[0] === 3) {
        task.complete_time = new Date();
      }
      return [{ affectedRows: 1 }];
    }
  }

  return [{ affectedRows: 0 }];
};

// 处理DELETE查询
const handleDelete = (sql, params) => {
  return [{ affectedRows: 1 }];
};

// 执行函数（与query相同）
export const execute = query;

// 事务函数
export const transaction = async (callback) => {
  try {
    const conn = {
      query: query,
      execute: execute
    };

    const result = await callback(conn);
    return result;
  } catch (error) {
    throw error;
  }
};

// 数据库健康检查
export const healthCheck = async () => {
  try {
    const startTime = Date.now();
    await testConnection();
    const responseTime = Date.now() - startTime;

    return {
      status: 'healthy',
      timestamp: new Date().toISOString(),
      response_time_ms: responseTime,
      database_type: 'Temporary Database (Development)',
      database_host: 'In-Memory',
      database_name: 'endo_sight_uc_dev',
      statistics: {
        doctors: tempData.doctors.size,
        patients: tempData.patients.size,
        scoring_tasks: tempData.scoring_tasks.size,
        scoring_results: tempData.scoring_results.size,
        system_logs: tempData.system_logs.length
      }
    };
  } catch (error) {
    return {
      status: 'unhealthy',
      timestamp: new Date().toISOString(),
      error: error.message,
      database_type: 'Temporary Database (Development)'
    };
  }
};

// 初始化数据库
export const initialize = async () => {
  try {
    await initializeDatabase();
    logger.info('🎉 临时数据库完全初始化完成');
    return true;
  } catch (error) {
    logger.error('❌ 临时数据库初始化失败:', error);
    throw error;
  }
};

// 确保数据库在使用前初始化
export const ensureInitialized = async () => {
  // 临时数据库总是已初始化的
  return true;
};

// 更新性能统计
const updatePerformanceStats = (sql, queryTime, success) => {
  performanceStats.totalQueries++;

  if (!success) {
    performanceStats.errorCount++;
  }

  performanceStats.queryTimes.push(queryTime);

  // 只保留最近1000次查询的时间记录
  if (performanceStats.queryTimes.length > 1000) {
    performanceStats.queryTimes = performanceStats.queryTimes.slice(-1000);
  }

  // 检查是否为慢查询
  if (queryTime > 1000) {
    performanceStats.slowQueries++;
    logger.warn(`🐌 慢查询检测:`, {
      sql: sql.substring(0, 100) + (sql.length > 100 ? '...' : ''),
      queryTime: `${queryTime}ms`
    });
  }

  // 计算平均查询时间
  const sum = performanceStats.queryTimes.reduce((a, b) => a + b, 0);
  performanceStats.averageQueryTime = Math.round(sum / performanceStats.queryTimes.length);
};

// 获取性能统计信息
export const getPerformanceStats = () => {
  const uptime = Date.now() - performanceStats.lastReset.getTime();

  return {
    ...performanceStats,
    uptime_ms: uptime,
    slowQueryRate: performanceStats.totalQueries > 0
      ? Math.round((performanceStats.slowQueries / performanceStats.totalQueries) * 100 * 100) / 100
      : 0,
    errorRate: performanceStats.totalQueries > 0
      ? Math.round((performanceStats.errorCount / performanceStats.totalQueries) * 100 * 100) / 100
      : 0,
    qps: uptime > 0 ? Math.round((performanceStats.totalQueries / uptime) * 1000) : 0
  };
};

// 重置性能统计
export const resetPerformanceStats = () => {
  performanceStats.totalQueries = 0;
  performanceStats.slowQueries = 0;
  performanceStats.averageQueryTime = 0;
  performanceStats.queryTimes = [];
  performanceStats.errorCount = 0;
  performanceStats.lastReset = new Date();
  logger.info('📊 性能统计已重置');
};

export default {
  query,
  execute,
  testConnection,
  transaction,
  healthCheck,
  initialize,
  ensureInitialized,
  getPerformanceStats,
  resetPerformanceStats
};